<template>
  <a-form class="add-salary-form" layout="vertical">
    <!-- 标题区域 -->
    <div class="form-title">
      <h2>添加薪酬信息</h2>
      <p class="tip">请填写准确的薪酬信息，帮助建立更好的行业薪酬数据库</p>
    </div>
    
    <!-- 图一内容：基本信息和薪酬信息 -->
    <a-row :gutter="20" class="equal-height-cols">
      <!-- 基本信息区域 -->
      <a-col :span="24">
        <a-card class="form-section">
          <div class="section-title">
            <span class="icon">$</span> 基本信息
          </div>
          <a-form-item label="标题 *" required>
            <a-input v-model:value="salaryData.title" placeholder="请输入标题" />
          </a-form-item>
          <a-form-item label="公司名称 *" required>
            <a-select 
              v-model:value="selectedCompany" 
              placeholder="请选择公司名称" 
              style="width: 100%"
              :filter-option="false"
              :options="companyOptions.map(item => ({ value: item.id, label: item.name }))"
              :loading="companyLoading"
              @change="handleCompanyChange"
            >
            </a-select>
          </a-form-item>
          
          <a-form-item label="岗位名称 *" required>
            <a-input v-model:value="jobTitle" placeholder="请输入岗位名称" />
          </a-form-item>
          
          <a-row :gutter="20">
            <a-col :span="12">
              <a-form-item label="职级 *" required>
                <a-select 
                  v-model:value="salaryData.level_id" 
                  placeholder="请选择职级" 
                  style="width: 100%"
                  :loading="levelLoading"
                  :disabled="!selectedCompany"
                  :options="levelOptions.map(item => ({ value: item.id, label: item.level_name }))"
                >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="工作方向 *" required>
                <a-select v-model:value="selectedFocus" placeholder="请选择工作方向" style="width: 100%" mode="multiple">
                  <a-select-option value="frontend">前端开发</a-select-option>
                  <a-select-option value="backend">后端开发</a-select-option>
                  <a-select-option value="test">测试</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          
          <a-form-item label="所在地区 *" required>
            <a-select v-model:value="salaryData.location" placeholder="请选择所在地区" style="width: 100%">
              <a-select-option value="beijing">北京</a-select-option>
              <a-select-option value="shanghai">上海</a-select-option>
              <a-select-option value="shenzhen">深圳</a-select-option>
              <a-select-option value="hangzhou">杭州</a-select-option>
              <a-select-option value="guangzhou">广州</a-select-option>
            </a-select>
          </a-form-item>
        </a-card>
      </a-col>
      

      <!-- 薪酬信息区域 -->
      <a-col :span="24">
        <a-card class="form-section">
          <div class="section-title">
            <span class="icon">E</span> 薪酬信息
          </div>
          
          <a-form-item label="月薪（税前） *" required>
            <div class="slider-value">{{ formatCurrency(monthlySalary) }}</div>
            <a-slider v-model:value="monthlySalary" :min="0" :max="100000" :step="1000" />
            <div class="slider-range">
              <span>0</span>
              <span>10万</span>
            </div>
          </a-form-item>
          
          <a-form-item label="年终奖金">
            <div class="slider-value">{{ formatCurrency(bonus) }}</div>
            <a-slider v-model:value="bonus" :min="0" :max="1000000" :step="1000" />
            <div class="slider-range">
              <span>0</span>
              <span>100万</span>
            </div>
          </a-form-item>
          
          <a-form-item label="股票期权">
            <div class="slider-value">{{ formatCurrency(stock) }}</div>
            <a-slider v-model:value="stock" :min="0" :max="1000000" :step="1000" />
            <div class="slider-range">
              <span>0</span>
              <span>100万</span>
            </div>
          </a-form-item>
          
          <a-form-item label="薪酬类别 *" required>
            <a-select v-model:value="salaryData.hire_type" placeholder="请选择薪酬类别" style="width: 100%">
              <a-select-option value="tech">技术类</a-select-option>
              <a-select-option value="management">管理类</a-select-option>
              <a-select-option value="sales">销售类</a-select-option>
            </a-select>
          </a-form-item>
        </a-card>
      </a-col>
    </a-row>
    
    <!-- 图二内容：个人背景和技术栈 -->
    <a-card class="form-section">
      <div class="section-title">
        <span class="icon">O</span> 个人背景
      </div>
      
      <a-row :gutter="20">
        <!-- 左列 -->
        <a-col :span="24">
          <a-row :gutter="20">
            <a-col :span="12">
              <a-form-item label="工作年限 *" required>
                <a-select v-model:value="salaryData.year_of_experience" placeholder="请选择工作年限">
                  <a-select-option v-for="n in 30" :key="n" :value="n">{{ n }}年</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="学历 *" required>
                <a-select v-model:value="salaryData.degree" placeholder="请选择学历">
                  <a-select-option value="college">大专</a-select-option>
                  <a-select-option value="bachelor">本科</a-select-option>
                  <a-select-option value="master">硕士</a-select-option>
                  <a-select-option value="phd">博士</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          
          <a-form-item label="本科学校">
            <a-input v-model:value="salaryData.bachelor_school" placeholder="请输入本科学校" />
          </a-form-item>
          
          <a-form-item label="性别">
            <a-select v-model:value="gender" placeholder="请选择性别">
              <a-select-option value="male">男</a-select-option>
              <a-select-option value="female">女</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        
        <!-- 右列 -->
        <a-col :span="24">
          <a-form-item label="研究生学校">
            <a-input v-model:value="salaryData.advanced_school" placeholder="请输入研究生学校" />
          </a-form-item>
          
          <a-form-item label="每周工作小时 *" required>
            <a-input-number v-model:value="salaryData.hour_per_week" :min="10" :max="80" />
            <span class="hours-text">小时</span>
          </a-form-item>
        </a-col>
      </a-row>
      
      <!-- 技术栈区域 -->
      <div class="other-section">
        <div class="subtitle">其他信息</div>
        
        <a-form-item label="技术栈 *" required>
          <div class="tech-tags">
            <a-tag v-for="tag in selectedTech" :key="tag" closable @close="removeTech(tag)">
              {{ tag }}
            </a-tag>
          </div>
          
          <a-select 
            v-model:value="selectedTechOption" 
            placeholder="请选择技术栈" 
            class="tech-select"
            @change="addTechFromSelect"
          >
            <a-select-option 
              v-for="item in techOptions" 
              :key="item" 
              :value="item"
            >
              {{ item }}
            </a-select-option>
          </a-select>
          
          <div class="custom-tech">
            <a-input v-model:value="customTech" placeholder="输入自定义技术栈" />
            <a-button type="primary" @click="addCustomTech">添加</a-button>
          </div>
        </a-form-item>
      </div>
      
      <!-- 底部按钮 -->
      <div class="form-footer">
        <a-button @click="cancelSubmit">取消</a-button>
        <a-button type="primary" @click="submitSalary" :loading="submitLoading">提交薪酬信息</a-button>
      </div>
    </a-card>
  </a-form>
</template>


<script>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { SalariesdataApi, CampatydataApi, userApi } from '@/utils/api';

export default {
  name: 'AddSalary',
  setup() {
    // 薪酬数据
    const monthlySalary = ref(20000);
    const bonus = ref(50000);
    const stock = ref(200000);
    const jobTitle = ref('');
    const selectedFocus = ref([]);
    const gender = ref('');
    const selectedCompany = ref(''); // 新增：用于存储选中的公司ID

    // 公司和职级相关数据
    const companyOptions = ref([]);
    const levelOptions = ref([]);
    const companyLoading = ref(false);
    const levelLoading = ref(false);

    // 提交加载状态
    const submitLoading = ref(false);

    // 薪酬数据对象
    const salaryData = reactive({
      title: '',
      department: '', // 公司名称
      tech_stacks: [],
      focuses: [],
      hire_type: '',
      country: '中国',
      location: '',
      hour_per_week: 40,
      base_comp: 0,
      base_monthly_comp: 0,
      base_monthly_comp_multiplier: 0,
      bonus_comp: 0,
      bonus_comp_multiplier: 0,
      stock_comp: 0,
      annual_stock_num: 0,
      total_comp: 0,
      year_in_company: 0,
      year_of_experience: 1,
      degree: '',
      bachelor_school: '',
      advanced_school: '',
      currency_code: 'CNY',
      is_anonymous: false,
      is_current: true,
      user_id: "a1f51a6d-c4d2-47ee-a970-a9c58ce89b3a",
      company_id: "", // 公司ID
      level_id: "",
      thread_id: "3fa85f64-5717-4562-b3fc-2c963f66afa6"
    });

    // 技术栈相关数据
    const selectedTech = ref(['JavaScript', 'React', 'Node.js']);
    const selectedTechOption = ref('');
    const customTech = ref('');
    const techOptions = [
      'Python', 'Java', 'Go', 'TypeScript', 
      'MySQL', 'Redis', 'Docker', 'Kubernetes', 'AWS'
    ];

    // 页面加载时获取公司列表和用户信息
    onMounted(() => {
      fetchCompanies();
      fetchUserInfo();
    });

    // 获取当前登录用户信息
    const fetchUserInfo = async () => {
      try {
        const response = await userApi.getUserInfo();
        const userInfo = response.data || response;
        salaryData.user_id = userInfo.id || "";
      } catch (error) {
        message.error('获取用户信息失败: ' + (error.message || '未知错误'));
        console.error('获取用户信息失败:', error);
      }
    };

    // 获取公司列表
    const fetchCompanies = async () => {
      companyLoading.value = true;
      try {
        const response = await CampatydataApi.getCampatyDataList();
        companyOptions.value = response.data || response;
      } catch (error) {
        message.error('获取公司列表失败: ' + (error.message || '未知错误'));
        console.error('获取公司列表失败:', error);
      } finally {
        companyLoading.value = false;
      }
    };

    // 处理公司选择变化
    const handleCompanyChange = async (companyId) => {
      if (!companyId) {
        levelOptions.value = [];
        salaryData.level_id = "";
        salaryData.company_id = "";
        return;
      }
      
      // 设置公司ID
      salaryData.company_id = companyId;
      
      levelLoading.value = true;
      try {
        const response = await CampatydataApi.getLevelsByCompanyId(companyId);
        levelOptions.value = response.data || response;
        salaryData.level_id = "";
      } catch (error) {
        message.error('获取职级列表失败: ' + (error.message || '未知错误'));
        console.error('获取职级列表失败:', error);
      } finally {
        levelLoading.value = false;
      }
    };

    // 技术操作方法
    const addTechFromSelect = () => {
      if (selectedTechOption.value && !selectedTech.value.includes(selectedTechOption.value)) {
        selectedTech.value.push(selectedTechOption.value);
        selectedTechOption.value = '';
      }
    };

    const addCustomTech = () => {
      if (customTech.value.trim() && !selectedTech.value.includes(customTech.value.trim())) {
        selectedTech.value.push(customTech.value.trim());
        customTech.value = '';
      }
    };

    const removeTech = (tag) => {
      selectedTech.value = selectedTech.value.filter(t => t !== tag);
    };

    // 格式化货币显示
    const formatCurrency = (value) => {
      if (value >= 10000) {
        return (value / 10000).toFixed(1) + '万';
      }
      return value.toLocaleString() + '元';
    };

    // 提交薪酬信息
    const submitSalary = async () => {
      try {
        submitLoading.value = true;
        
        // 更新薪酬数据对象
        const submitData = { ...salaryData };
        submitData.tech_stacks = selectedTech.value;
        submitData.focuses = selectedFocus.value;
        submitData.base_monthly_comp = monthlySalary.value;
        submitData.bonus_comp = bonus.value;
        submitData.stock_comp = stock.value;
        submitData.total_comp = monthlySalary.value * 12 + bonus.value + stock.value;
        
        // 设置公司名称（根据选中的公司ID查找公司名称）
        const selectedCompanyObj = companyOptions.value.find(company => company.id === selectedCompany.value);
        if (selectedCompanyObj) {
          submitData.department = selectedCompanyObj.name;
        }
        
        // 发送POST请求
        const response = await SalariesdataApi.submitSalary(submitData);
        message.success('薪酬信息提交成功！');
        console.log('提交成功:', response);
      } catch (error) {
        message.error('提交失败: ' + (error.message || '未知错误'));
        console.error('提交失败:', error);
      } finally {
        submitLoading.value = false;
      }
    };

    // 取消提交
    const cancelSubmit = () => {
      // 这里可以添加确认对话框
      message.info('已取消提交');
    };

    return {
      monthlySalary,
      bonus,
      stock,
      jobTitle,
      selectedFocus,
      gender,
      selectedCompany,
      companyOptions,
      levelOptions,
      companyLoading,
      levelLoading,
      submitLoading,
      salaryData,
      selectedTech,
      selectedTechOption,
      customTech,
      techOptions,
      fetchUserInfo,
      fetchCompanies,
      handleCompanyChange,
      addTechFromSelect,
      addCustomTech,
      removeTech,
      formatCurrency,
      submitSalary,
      cancelSubmit
    };
  }
};
</script>
// ... existing code ...

<style scoped>
.add-salary-form {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.form-title {
  margin-bottom: 25px;
}

.form-title h2 {
  margin-bottom: 10px;
  color: #303133;
}

.tip {
  color: #909399;
  font-size: 14px;
}

.form-section {
  margin-bottom: 20px;
  border-radius: 4px;
}

.section-title {
  font-weight: bold;
  margin-bottom: 20px;
  font-size: 16px;
  color: #303133;
}

.icon {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 24px;
  height: 24px;
  background: #f0f7ff;
  border-radius: 4px;
  margin-right: 8px;
  color: #409EFF;
}

.slider-value {
  color: #409EFF;
  font-weight: bold;
  margin-bottom: 5px;
}

.slider-range {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
  margin-top: -10px;
}

.tech-tags {
  margin-bottom: 10px;
}

.tech-tags .el-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.tech-select {
  width: 100%;
  margin-bottom: 10px;
}

.custom-tech {
  display: flex;
  margin-top: 10px;
}

.custom-tech .el-input {
  margin-right: 10px;
}

.form-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.form-footer .el-button {
  margin-left: 10px;
}

.hours-text {
  margin-left: 10px;
  color: #606266;
}

.other-section {
  margin-top: 30px;
}

.subtitle {
  font-weight: 600;
  font-size: 15px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

/* 添加等高列的样式 */
.equal-height-cols {
  display: flex;
  align-items: stretch;
}

.equal-height-cols .el-card {
  height: 95%;
  display: flex;
  flex-direction: column;
}

.equal-height-cols .el-card .el-card__body {
  flex: 1;
  display: flex;
  flex-direction: column;
}
</style>